<template>
  <el-breadcrumb class="app-breadcrumb" separator="/">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item,index) in levelList" :key="item.path">
        <span v-if="item.redirect==='noRedirect'||index==levelList.length-1" class="no-redirect">{{ item.meta.title }}</span>
        <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>
<script>
import { watch,reactive,ref } from 'vue'
import { compile as pathRegCompile}  from 'path-to-regexp'
import { useRoute, useRouter } from 'vue-router'
export default {
  setup(props){
    // 获取路由对象 
    const route = useRoute()
    const router = useRouter()
    let levelList = ref([])
    function isIndex(route) {
      const name = route && route.name
      if (!name) {
        return false
      }
      return name.trim().toLocaleLowerCase() === 'index'.toLocaleLowerCase()
    }
    
    // 将路由转成面包屑
    function getBreadcrumb(){
      // console.log('route:',route)
      let matched = route.matched.filter(item => item.meta && item.meta.title)
      const first = matched[0]
      if (!isIndex(first)) {
        matched = [{ path: '/index', meta: { title: '首页' }}].concat(matched)
      }
      levelList.value = matched.filter(item => item.meta && item.meta.title && item.meta.breadcrumb !== false)
    }

    // 对路由进行解析

    function pathCompile(path){
      let params = route.params
      let toPath = pathRegCompile(path)
      let targetPath = toPath(params)
      return targetPath
    }
    // 点击跳转
    function handleLink(item){
      let  { redirect , path } =  item
      if(redirect){
        router.push(redirect)
        return 
      }else {
        router.push(pathCompile(path))
      }
    }
    // 监听路由的变化
    
    watch(()=> route.path,()=>{
      if(route.path.startsWith('/redirect/')){
        return 
      }
      getBreadcrumb()
    })

    getBreadcrumb()

    return {
      levelList,
      handleLink
    }
    
    

    
    

    
  }
}
</script>
